package com.gzhryc.shared_device.oem.code.business.services;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.base.enums.ECouponType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.oem.code.business.dao.CouponActivityDao;
import com.gzhryc.shared_device.oem.code.business.dao.db.CouponActivity;
import com.gzhryc.shared_device.oem.code.business.dao.db.CouponActivityPlace;
import com.gzhryc.shared_device.oem.code.business.dao.enums.CouponActivityEnum;
import com.gzhryc.shared_device.oem.code.business.dao.enums.CouponActivityPlaceEnum;
import com.gzhryc.shared_device.oem.code.business.services.dto.CouponActivitySearch;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberBusinessOrder;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberCoupon;
import com.gzhryc.shared_device.oem.code.member.services.*;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class CouponActivityService {

    static Logger log = Logger.getLogger(CouponActivityService.class);

    public static CouponActivityService self() {
        return MultiDBTools.getService(CouponActivityService.class, true);
    }

    public static CouponActivityService self(String jdbcKey) {
        return MultiDBTools.getService(jdbcKey, CouponActivityService.class, true);
    }

    CouponActivityDao dao;

    public CouponActivityService(String jdbcKey) {
        this.dao = new CouponActivityDao(jdbcKey);
    }

    public List<CouponActivity> findJoinBySearch(CouponActivitySearch search, Integer pageNo, Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        conditions.desc("createDate");
        try {
            return dao.findJoinByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public Long countJoinBySearch(CouponActivitySearch search){
        Conditions conditions = dao.buildConditions(search);
        try {
            return dao.countJoin(conditions);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return 0L;
    }

    public List<CouponActivity> findBySearch(CouponActivitySearch search1,CouponActivitySearch search2, Integer pageNo, Integer pageLimit){
        try {
            Conditions conditions1 = dao.buildConditions(search1);
            Conditions conditions2 = dao.buildConditions(search2);
            return dao.findBySearch(conditions1,conditions2,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public List<CouponActivity> findEnableByType(Integer couponType,Integer type){
        if(couponType != null && type != null) {
            Conditions conditions = new Conditions(CouponActivity.class);
            conditions.and().is("type", type);
            conditions.and().is("couponType", couponType);
            conditions.and().is("state",CouponActivityEnum.State.Enable.index());
            conditions.desc("createDate");

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public List<CouponActivity> findEnableByType(Integer type){
        if(type != null) {
            Conditions conditions = new Conditions(CouponActivity.class);
            conditions.and().is("type", type);
            conditions.and().is("state",CouponActivityEnum.State.Enable.index());
            conditions.desc("createDate");

            try {
                return dao.findByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public CouponActivity getJoinById(Long id){
        try {
            return dao.getJoinById(id);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public boolean add(CouponActivity couponActivity) throws LogicException {
        if(CouponActivityEnum.UseLimit.LimitBusinessType.index().equals(couponActivity.getUseLimit())){
            if(StringTools.isBlank(couponActivity.getBusinessType())){
                throw new LogicException("请填写业务类型");
            }
        }else {
            couponActivity.setBusinessType(null);
        }

        if(ECouponType.VOUCHERS.index().equals(couponActivity.getCouponType())){
            if(couponActivity.getCouponMoney() == null || couponActivity.getCouponMoney() <= 0){
                throw new LogicException("请填写优惠金额");
            }
        }else if(ECouponType.DISCOUNT_COUPON.index().equals(couponActivity.getCouponType())){
            if(couponActivity.getCouponDiscount() == null || couponActivity.getCouponDiscount() <= 0){
                throw new LogicException("请填写折扣信息");
            }
        }else if(ECouponType.COUPON_DAY.index().equals(couponActivity.getCouponType())){
            if(couponActivity.getCouponDay() == null || couponActivity.getCouponDay() <= 0){
                throw new LogicException("请填写优惠天数");
            }
        }else {
            throw new LogicException("无效的优惠类型");
        }

        couponActivity.setUseRange(CouponActivityEnum.UseRange.Unlimited.index());
        couponActivity.setCreateDate(new Date());
        if(couponActivity.getCreateDate().after(couponActivity.getStartDate())) {
            couponActivity.setState(CouponActivityEnum.State.Enable.index());
        }else{
            couponActivity.setState(CouponActivityEnum.State.WaitEnable.index());
        }
        try {
            return dao.insert(couponActivity) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    /**
     * 新人注册优惠活动，不限制网点，不限制业务类型
     * @param couponActivity
     * @param memberId
     * @param memberName
     * @return
     */
    public boolean memberNewReceive(CouponActivity couponActivity,Long memberId,String memberName, OperateInfo operateInfo) throws LogicException {
        if(couponActivity != null && memberId != null && CouponActivityEnum.Type.NewPeople.index().equals(couponActivity.getType())) {
            Date currentDate = new Date();
            //检查是否过去
            if (!CouponActivityEnum.State.Enable.index().equals(couponActivity.getState()) || currentDate.after(couponActivity.getEndDate())) {
                throw new LogicException("优惠活动已过期");
            }

            MemberCoupon memberCoupon = MemberCouponService.self().getNormalByActivityId(couponActivity.getId());
            if (memberCoupon != null) {
                throw new LogicException("已参加优惠活动");
            }

            memberCoupon = new MemberCoupon();
            memberCoupon.setMemberId(memberId);
            memberCoupon.setMemberName(memberName);
            memberCoupon.setActivityId(couponActivity.getId());
            memberCoupon.setCouponType(couponActivity.getCouponType());
            memberCoupon.setCouponMoney(couponActivity.getCouponMoney());
            memberCoupon.setCouponDiscount(couponActivity.getCouponDiscount());
            memberCoupon.setCouponDay(couponActivity.getCouponDay());
            memberCoupon.setMinimumCharge(couponActivity.getMinimumCharge());
            memberCoupon.setUseRange(couponActivity.getUseRange());
            memberCoupon.setUseLimit(couponActivity.getUseLimit());
            memberCoupon.setBusinessType(couponActivity.getBusinessType());
            memberCoupon.setNote(couponActivity.getNote());
            memberCoupon.setExpirationDate(couponActivity.getEndDate());

            JdbcSession.begin();
            try {
                Conditions conditions = new Conditions(CouponActivity.class);
                conditions.and().is("id", couponActivity.getId());
                conditions.and().is("state", CouponActivityEnum.State.Enable.index());

                CouponActivity updateEntity = new CouponActivity();
                updateEntity.setCouponCount(1);

                if (dao.updateNotNullAndInc(updateEntity, conditions, "couponCount") > 0) {
                    if (MemberCouponService.self().add(memberCoupon)) {
                    	 JdbcSession.commit();
                         return true;
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            } finally {
                JdbcSession.end();
            }
        }
        return false;
    }

    /**
     * 会员主动领取(扫码领取)
     * @param couponActivity
     * @param memberId
     * @param memberName
     * @param placeId
     * @param operateInfo
     * @return
     * @throws LogicException
     */
    public boolean memberScanReceive(CouponActivity couponActivity,Long memberId,String memberName,Long placeId, OperateInfo operateInfo) throws LogicException {
        if (couponActivity != null && memberId != null) {
            Date currentDate = new Date();
            //检查是否过去
            if (!CouponActivityEnum.State.Enable.index().equals(couponActivity.getState()) || currentDate.after(couponActivity.getEndDate())) {
                throw new LogicException("优惠活动已过期");
            }

            if (CouponActivityEnum.UseRange.DesignatedPlace.index().equals(couponActivity.getUseRange())) {
                if (placeId == null) {
                    throw new LogicException("优惠活动指定网点，请选择优惠的网点");
                }

                CouponActivityPlace couponActivityPlace = CouponActivityPlaceService.self().getByKeys(couponActivity.getId(), placeId);
                if (couponActivityPlace == null || CouponActivityPlaceEnum.State.Disable.index().equals(couponActivity.getState())) {
                    throw new LogicException("当前网点不参与该优惠活动");
                }
            }

            MemberCoupon memberCoupon = MemberCouponService.self().getNormalByActivityId(couponActivity.getId());
            if (memberCoupon != null) {
                throw new LogicException("已参加优惠活动");
            }

            memberCoupon = new MemberCoupon();
            memberCoupon.setMemberId(memberId);
            memberCoupon.setMemberName(memberName);
            memberCoupon.setActivityId(couponActivity.getId());
            memberCoupon.setCouponType(couponActivity.getCouponType());
            memberCoupon.setCouponMoney(couponActivity.getCouponMoney());
            memberCoupon.setCouponDiscount(couponActivity.getCouponDiscount());
            memberCoupon.setCouponDay(couponActivity.getCouponDay());
            memberCoupon.setMinimumCharge(couponActivity.getMinimumCharge());
            memberCoupon.setUseRange(couponActivity.getUseRange());
            memberCoupon.setUseLimit(couponActivity.getUseLimit());
            memberCoupon.setBusinessType(couponActivity.getBusinessType());
            memberCoupon.setNote(couponActivity.getNote());
            memberCoupon.setExpirationDate(couponActivity.getEndDate());

            JdbcSession.begin();
            try {
                Conditions conditions = new Conditions(CouponActivity.class);
                conditions.and().is("id", couponActivity.getId());
                conditions.and().is("state", CouponActivityEnum.State.Enable.index());

                CouponActivity updateEntity = new CouponActivity();
                updateEntity.setCouponCount(1);

                if (dao.updateNotNullAndInc(updateEntity, conditions, "couponCount") > 0) {
                    if (MemberCouponService.self().add(memberCoupon)) {
                        if (CouponActivityEnum.UseRange.DesignatedPlace.index().equals(couponActivity.getUseRange())) {
                            if (CouponActivityPlaceService.self().addCouponCount(couponActivity.getId(), placeId)) {
                                JdbcSession.commit();
                                return true;
                            }
                        } else {
                            JdbcSession.commit();
                            return true;
                        }
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            } finally {
                JdbcSession.end();
            }
        }
        return false;
    }

    /**
     * 订单完成自动领取
     * @param memberBusinessOrder
     * @param couponType
     * @return
     * @throws LogicException
     */
    public int memberOrderReceive(MemberBusinessOrder memberBusinessOrder,Integer couponType) throws LogicException {
        if(memberBusinessOrder != null && memberBusinessOrder.getVerificationVoucherState() == 0) {
            List<CouponActivity> couponActivityList = CouponActivityService.self().findEnableByType(couponType, CouponActivityEnum.Type.OrderFinish.index());
            if (couponActivityList != null && couponActivityList.size() > 0) {
                for (CouponActivity couponActivity : couponActivityList) {
                    boolean flag = true;
                    if (CouponActivityEnum.UseLimit.LimitBusinessType.index().equals(couponActivity.getUseLimit())) {
                        if (!memberBusinessOrder.getBusinessType().equals(couponActivity.getBusinessType())) {
                            flag = false;
                        }
                    }

                    if (flag) {
                        //检查网点
                        if (CouponActivityEnum.UseRange.DesignatedPlace.index().equals(couponActivity.getUseRange())) {
                            CouponActivityPlace couponActivityPlace = CouponActivityPlaceService.self().getByKeys(couponActivity.getId(), memberBusinessOrder.getPlaceId());
                            if (couponActivityPlace == null) {
                                flag = false;
                            }
                        }
                    }

                    if (flag) {
                        //---
                    }
                }
            }
        }
        return -1;
    }

    /**
     * 代理手动发放
     * @param couponActivity
     * @param memberId
     * @param memberName
     * @param placeId
     * @param operateInfo
     * @return
     * @throws LogicException
     */
    public boolean memberReceive(CouponActivity couponActivity,Long memberId,String memberName,Long placeId, OperateInfo operateInfo) throws LogicException {
        if (couponActivity != null && memberId != null) {
            if(!CouponActivityEnum.Type.HandSend.index().equals(couponActivity.getType())){
                throw new LogicException("非手动发放的优惠活动");
            }
            Date currentDate = new Date();
            //检查是否过去
            if (!CouponActivityEnum.State.Enable.index().equals(couponActivity.getState()) || currentDate.after(couponActivity.getEndDate())) {
                throw new LogicException("优惠活动已过期");
            }

            if (CouponActivityEnum.UseRange.DesignatedPlace.index().equals(couponActivity.getUseRange())) {
                if (placeId == null) {
                    throw new LogicException("优惠活动指定网点，请选择优惠的网点");
                }

                CouponActivityPlace couponActivityPlace = CouponActivityPlaceService.self().getByKeys(couponActivity.getId(), placeId);
                if (couponActivityPlace == null || CouponActivityPlaceEnum.State.Disable.index().equals(couponActivity.getState())) {
                    throw new LogicException("当前网点不参与该优惠活动");
                }
            }
            
            //领取折扣券，代金券，免租金券
            MemberCoupon memberCoupon = new MemberCoupon();
            memberCoupon.setMemberId(memberId);
            memberCoupon.setMemberName(memberName);
            memberCoupon.setActivityId(couponActivity.getId());
            memberCoupon.setCouponType(couponActivity.getCouponType());
            memberCoupon.setCouponMoney(couponActivity.getCouponMoney());
            memberCoupon.setCouponDiscount(couponActivity.getCouponDiscount());
            memberCoupon.setCouponDay(couponActivity.getCouponDay());
            memberCoupon.setMinimumCharge(couponActivity.getMinimumCharge());
            memberCoupon.setUseRange(couponActivity.getUseRange());
            memberCoupon.setUseLimit(couponActivity.getUseLimit());
            memberCoupon.setBusinessType(couponActivity.getBusinessType());
            memberCoupon.setNote(couponActivity.getNote());
            memberCoupon.setExpirationDate(couponActivity.getEndDate());
 
            JdbcSession.begin();
            try {
                Conditions conditions = new Conditions(CouponActivity.class);
                conditions.and().is("id", couponActivity.getId());
                conditions.and().is("state", CouponActivityEnum.State.Enable.index());

                CouponActivity updateEntity = new CouponActivity();
                updateEntity.setCouponCount(1);

                if (dao.updateNotNullAndInc(updateEntity, conditions, "couponCount") > 0) {
                    if (MemberCouponService.self().add(memberCoupon)) {
                        if (CouponActivityEnum.UseRange.DesignatedPlace.index().equals(couponActivity.getUseRange())) {
                            if (CouponActivityPlaceService.self().addCouponCount(couponActivity.getId(), placeId)) {
                                JdbcSession.commit();
                                return true;
                            }
                        } else {
                            JdbcSession.commit();
                            return true;
                        }
                    }
                }
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            } finally {
                JdbcSession.end();
            }
        }
        return false;
    }

    public boolean updateNotNull(CouponActivity couponActivity) throws LogicException{
        if(CouponActivityEnum.UseLimit.LimitBusinessType.index().equals(couponActivity.getUseLimit())){
            if(StringTools.isBlank(couponActivity.getBusinessType())){
                throw new LogicException("请填写业务类型");
            }
        }else {
            couponActivity.setBusinessType(null);
        }

        if(ECouponType.VOUCHERS.index().equals(couponActivity.getCouponType())){
            if(couponActivity.getCouponMoney() == null || couponActivity.getCouponMoney() <= 0){
                throw new LogicException("请填写优惠金额");
            }
        }else if(ECouponType.DISCOUNT_COUPON.index().equals(couponActivity.getCouponType())){
            if(couponActivity.getCouponDiscount() == null || couponActivity.getCouponDiscount() <= 0){
                throw new LogicException("请填写折扣信息");
            }
        }else if(ECouponType.COUPON_DAY.index().equals(couponActivity.getCouponType())){
            if(couponActivity.getCouponDay() == null || couponActivity.getCouponDay() <= 0){
                throw new LogicException("请填写优惠天数");
            }
        }else {
            throw new LogicException("无效的优惠类型");
        }

        Date currentDate = new Date();
        if(currentDate.after(couponActivity.getStartDate())) {
            couponActivity.setState(CouponActivityEnum.State.Enable.index());
        }else{
            couponActivity.setState(CouponActivityEnum.State.WaitEnable.index());
        }
        try {
            return dao.updateNotNull(couponActivity,"businessType") > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return false;
    }

    public boolean updateUseRange(Long id,Integer useRange){
        if(id != null && useRange != null){
            CouponActivity couponActivity = new CouponActivity();
            couponActivity.setId(id);
            couponActivity.setUseRange(useRange);

            try {
                return dao.updateNotNull(couponActivity) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(),e);
            }
        }
        return false;
    }

    public boolean deleteById(Long id) throws LogicException{
        JdbcSession.begin();
        try {
            if(dao.deleteById(id) > 0){
                if(CouponActivityPlaceService.self().deleteByActivityId(id)){
                    JdbcSession.commit();
                    return true;
                }
            }
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }finally {
            JdbcSession.end();
        }
        return false;
    }

}
